package org.hlopik.riverGuide.client.view;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.VerticalPanel;
import java.util.ArrayList;
import java.util.List;
import org.hlopik.riverGuide.client.ApplicationFacade;
import org.hlopik.riverGuide.client.model.dto.RiverGuideDTO;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.mediator.Mediator;

/**
 *
 * @author f
 */
public class RiverGuideListMediator extends Mediator {

    public static final String NAME = "RiverGuideListMediator";
    private FlexTable table = new FlexTable();
    private List<RiverGuideDTO> riverGuides = new ArrayList<RiverGuideDTO>();
    private DialogBox dialogBox;
    private int tableRowPointer = 0;

    public RiverGuideListMediator() {
        super(NAME, null);
        initView();
    }

    @Override
    public String[] listNotificationInterests() {
        return new String[]{ApplicationFacade.GET_RIVER_GUIDES_SUCCESS,
                    ApplicationFacade.GET_RIVER_GUIDES_FAULT,
                    ApplicationFacade.ADD_RIVER_GUIDE_SUCCESS};
    }

    @Override
    @SuppressWarnings("unchecked")
    public void handleNotification(INotification notification) {
        String name = notification.getName();
        if (ApplicationFacade.GET_RIVER_GUIDES_FAULT.equals(name)) {
            Window.alert("GetRiverGuides failed");
        } else if (ApplicationFacade.GET_RIVER_GUIDES_SUCCESS.equals(name)) {
            riverGuides = (List<RiverGuideDTO>) notification.getBody();
            updateTable();
        } else if (ApplicationFacade.ADD_RIVER_GUIDE_SUCCESS.equals(name)) {
            sendNotification(ApplicationFacade.GET_RIVER_GUIDES);
        }
    }

    private void initView() {
        VerticalPanel vp = new VerticalPanel();
        vp.add(table);       
        table.setCellSpacing(0);
        table.setCellPadding(0);
        table.setWidth("100%");
        insertToTable("Name:", "Description:");
        updateTable();
        setViewComponent(vp);        
    }

    private void updateTable() {
        tableRowPointer = 1;
        for (RiverGuideDTO riverGuideDTO : riverGuides) {
            insertToTable(riverGuideDTO.getName(), riverGuideDTO.getDescription());
        }
    }

    private void insertToTable(String name, String description) {
        table.setText(tableRowPointer, 0, name);
        table.setText(tableRowPointer, 1, description);
        tableRowPointer++;
    }
}
